package cn.com.msui.controller.identity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.msui.common.DBTool;
import cn.com.msui.common.MD5;
import cn.com.msui.common.UUIDHexGenerator;
import cn.com.msui.controller.BaseController;
import cn.com.msui.controller.JsonResult;
import cn.com.msui.domain.ViewItem;
import cn.com.msui.domain.identity.User;
import cn.com.msui.service.identity.UserService;

@Controller
@RequestMapping("/identity/user")
public class UserController extends BaseController {

	private static Logger logger = Logger.getLogger(UserController.class);
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(value = "/showListUsers", method = RequestMethod.GET)
	public String showUserList() {
		return "identity/listUsers";
	}

	@RequestMapping(value = "/showChgPwd", method = RequestMethod.GET)
	public String showChangePassword() {
		return "identity/chgPwd";
	}

	@RequestMapping("/showUser/{id}")
	public String showUser(@PathVariable String id, HttpServletRequest request) {
		try {
			User user = userService.getUserById(id);
			request.setAttribute("user", user);
		} catch (Exception e) {
		}
		return "identity/showUser";
	}

	@RequestMapping(value = "/regUser", method = RequestMethod.POST)
	public String addUser(User user) {
		user.setId(DBTool.uniqueIdGenerator());
		user.setCreateTime(new Date());
		try {
			userService.addUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(e);
		}
		return null;
	}

	@RequestMapping(value = "/regUser", method = RequestMethod.GET)
	public String showAddUser() {
		return "identity/regUser";
	}

	@RequestMapping(value = "/listUsers", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> listUsers(ViewItem view) {
		Map<String, Object> map = new HashMap<String, Object>();
		int totalCount = 0;
		List<User> userList = new ArrayList<User>();
		try {
			totalCount = userService.getTotalCount(null);
			if (totalCount > 0)
				userList = userService.getUsers(view, null);
			map.put("total", totalCount);
			map.put("rows", userList);
		} catch (Exception e) {
			logger.debug(e);
			e.printStackTrace();
		}
		return map;
	}

	@RequestMapping(value = "/removeUsers", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult removeUsers(String ids) {
		JsonResult json = new JsonResult(false, "用户删除失败！");
		try {
			if (ids != null && ids.length() > 0) {
				String[] userIds = ids.split(",");
				userService.removeUsers(userIds);
				json.setSuccess(true);
				json.setMsg("用户删除成功！");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/saveUser")
	@ResponseBody
	public JsonResult saveUser(User user, HttpServletRequest request) {
		JsonResult json = new JsonResult(false, "用户保存失败！");
		json.setObj(user);
		if (!StringUtils.hasText(user.getCreateIP()))
			user.setCreateIP(getIpAddr(request));

		if (user.getCreateTime() == null) {
			user.setCreateTime(new Date());
		}

		if (user.getPassword().length() != 32) {
			String password = user.getPassword();
			MD5 md5 = new MD5(password);
			user.setPassword(md5.compute());
		}

		try {
			if (StringUtils.hasText(user.getId())) {
				userService.modifyUser(user);
			} else {
				user.setId(UUIDHexGenerator.getInstance().generate());
				userService.addUser(user);
			}
			json.setSuccess(true);
			json.setMsg("用户保存成功！");
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/uniqueAccount", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult uniqueAccount(String account) {
		JsonResult json = new JsonResult(false, "用户账号不唯一！");
		try {
			if (StringUtils.hasText(account)) {
				User user = new User();
				user.setAccount(account);
				int total = userService.getTotalCount(user);
				if (total == 0) {
					json.setSuccess(true);
					json.setMsg("用户账号唯一！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/existAccount", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult existAccount(String account) {
		JsonResult json = new JsonResult(false, "用户账号不存在！");
		try {
			if (StringUtils.hasText(account)) {
				User user = new User();
				user.setAccount(account);
				int total = userService.getTotalCount(user);
				if (total > 0) {
					json.setSuccess(true);
					json.setMsg("用户账号存在！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult uniqueEmail(String account, String password, String repassword) {
		JsonResult json = new JsonResult(false, "密码修改失败！");
		try {
			if (StringUtils.hasText(account) && StringUtils.hasText(password) && StringUtils.hasText(repassword) && password.equals(repassword)) {
				User user = userService.getUserByAccount(account);
				if (user != null) {
					String userId = user.getId();
					User userData = new User();
					userData.setId(userId);
					MD5 md5 = new MD5(password);
					userData.setPassword(md5.compute());
					userService.modifyUser(userData);
					json.setSuccess(true);
					json.setMsg("密码修改成功！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}

	@RequestMapping(value = "/uniqueEmail", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult uniqueEmail(String email) {
		JsonResult json = new JsonResult(false, "用户邮件不唯一！");
		try {
			if (StringUtils.hasText(email)) {
				User user = new User();
				user.setEmail(email);
				int total = userService.getTotalCount(user);
				if (total == 0) {
					json.setSuccess(true);
					json.setMsg("用户邮件唯一！");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return json;
	}
}
